<template>
  <div class="scan-records">
    <div class="header">
      <el-row :gutter="20" class="mb-4">
        <el-col :span="8">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
        </el-col>
        <el-col :span="8">
          <el-switch
            v-model="showByBatch"
            active-text="按批次显示"
            inactive-text="常规显示"
            style="margin-left: 20px;"
          />
        </el-col>
        <el-col :span="8" style="text-align: right;">
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div ref="chartContainer" class="chart-container" :style="chartContainerStyle">
      <v-chart ref="chartRef" class="chart" :option="chartOption" :autoresize="true" />
    </div>
    
    <!-- 按批次显示 -->
    <div v-if="showByBatch && scanStore.batchConfig.enabled" class="batch-records">
      <div class="table-actions">
        <el-button 
          type="danger" 
          @click="handleDeleteSelected"
          :disabled="!selectedRows.length"
          size="small"
        >
          <el-icon><Delete /></el-icon>
          删除选中 ({{ selectedRows.length }})
        </el-button>
      </div>
      <el-collapse v-model="expandedBatches" v-loading="isTableLoading">
        <el-collapse-item 
          v-for="batch in paginatedBatches" 
          :key="batch.batchId" 
          :name="batch.batchId"
        >
          <template #title>
            <div class="batch-header">
              <span class="batch-id">批次: {{ formatBatchId(batch.batchId) }}</span>
              <span class="batch-time">{{ formatShortDate(batch.startTime) }}</span>
              <el-tag type="info" class="batch-code">{{ batch.keyCode }}</el-tag>
              <span class="batch-product">{{ batch.productName }}</span>
              <el-tag type="success" class="batch-count">{{ batch.count }} / {{ scanStore.batchConfig.batchSize }}</el-tag>
            </div>
          </template>
          
          <el-table
            :data="batch.records"
            style="width: 100%"
            :default-sort="{ prop: 'scanTime', order: 'descending' }"
            size="small"
            @selection-change="(rows) => handleBatchSelectionChange(rows, batch.batchId)"
          >
            <el-table-column 
              type="selection" 
              width="45"
            />
            
            <el-table-column 
              label="扫描时间" 
              width="180"
              sortable
              :sort-orders="['descending']"
              :sort-by="(row) => new Date(row.scanTime).getTime()"
            >
              <template #default="{ row }">
                {{ formatDate(row.scanTime) }}
              </template>
            </el-table-column>
            
            <el-table-column 
              label="扫码信息" 
              min-width="150"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ row.scanCode }}
              </template>
            </el-table-column>

            <el-table-column 
              label="产品编码" 
              min-width="120"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ getProductCode(row.keyCode) }}
              </template>
            </el-table-column>
            
            <el-table-column 
              label="产品名称" 
              prop="productName" 
              min-width="200"
              show-overflow-tooltip
            />
            
            <el-table-column 
              label="关键代码" 
              prop="keyCode" 
              width="120"
            />
            
            <el-table-column 
              label="状态" 
              width="100"
            >
              <template #default="{ row }">
                <el-tag type="success" effect="dark">成功</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="batchCurrentPage"
          v-model:page-size="batchPageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="filteredBatches.length"
        />
      </div>
    </div>
    
    <!-- 常规显示 -->
    <div v-else class="table-container">
      <div class="table-actions">
        <el-button 
          type="danger" 
          @click="handleDeleteSelected"
          :disabled="!selectedRows.length"
          size="small"
        >
          <el-icon><Delete /></el-icon>
          删除选中 ({{ selectedRows.length }})
        </el-button>
      </div>
      <el-table
        :data="paginatedRecords"
        style="width: 100%"
        :default-sort="{ prop: 'scanTime', order: 'descending' }"
        @selection-change="handleSelectionChange"
        default-expand-all
        v-loading="isTableLoading"
        element-loading-text="加载中..."
      >
        <el-table-column 
          type="selection" 
          width="45"
          fixed="left"
        />
        
        <el-table-column 
          type="expand"
          width="45"
          fixed="left"
        >
          <template #default="props">
            <div class="expanded-row">
              <p><strong>扫码信息:</strong> {{ props.row.scanCode || '-' }}</p>
              <p v-if="props.row.batchId"><strong>批次ID:</strong> {{ props.row.batchId }}</p>
              <p v-if="props.row.keyCode"><strong>关键代码:</strong> {{ props.row.keyCode }}</p>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="扫描时间" 
          width="180"
          sortable
          :sort-orders="['descending']"
          :sort-by="(row) => new Date(row.scanTime).getTime()"
          fixed="left"
        >
          <template #default="{ row }">
            {{ formatDate(row.scanTime) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          v-if="scanStore.batchConfig.enabled"
          label="批次" 
          width="100"
        >
          <template #default="{ row }">
            <el-tag v-if="row.batchId" size="small" type="info">
              {{ formatBatchId(row.batchId) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column 
          label="产品编码" 
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ getProductCode(row.keyCode) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          label="产品名称" 
          prop="productName" 
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column 
          label="关键代码" 
          prop="keyCode" 
          width="120"
        />
        
        <el-table-column 
          label="状态" 
          width="100"
        >
          <template #default="{ row }">
            <el-tag type="success" effect="dark">成功</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="filteredRecords.length"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Delete } from '@element-plus/icons-vue'
import { useScanStore } from '../stores/scan'
import { useProductStore } from '../stores/product'
import dayjs from 'dayjs'
import * as echarts from 'echarts/core'
import {
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import VChart, { THEME_KEY } from 'vue-echarts'
import { CanvasRenderer } from 'echarts/renderers'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import type { ScanRecord } from '../types'

// 注册必要的组件
echarts.use([
  CanvasRenderer,
  LineChart,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  UniversalTransition
])

// 注册 dayjs 插件
dayjs.extend(isSameOrBefore)

const scanStore = useScanStore()
const productStore = useProductStore()
const loading = ref(false)
const dateRange = ref<[Date, Date] | null>(null)
const currentPage = ref(1)
const pageSize = ref(20)

// 批次相关
const showByBatch = ref(true)
const batchCurrentPage = ref(1)
const batchPageSize = ref(5)

// 添加变量，用于存储展开的批次
const expandedBatches = ref<string[]>([])

// 添加分页性能优化相关变量
const isTableLoading = ref(false)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setHours(0, 0, 0, 0)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
]

// 过滤记录
const filteredRecords = computed(() => {
  let records = [...scanStore.records]

  // 按日期范围过滤
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    const [start, end] = dateRange.value
    records = records.filter((record: ScanRecord) => {
      const recordDate = new Date(record.scanTime)
      return recordDate >= start && recordDate <= end
    })
  }

  return records
})

// 分页后的记录
const paginatedRecords = computed(() => {
  isTableLoading.value = true; // 开始加载
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  // 对记录进行倒序排序
  const result = filteredRecords.value
    .sort((a: ScanRecord, b: ScanRecord) => 
      new Date(b.scanTime).getTime() - new Date(a.scanTime).getTime()
    )
    .slice(start, end);
    
  // 加载完成
  nextTick(() => {
    isTableLoading.value = false;
  });
    
  return result;
})

// 批次相关计算属性
const filteredBatches = computed(() => {
  // 获取批次分组记录
  let batches = [...scanStore.getRecordsByBatch]
  
  // 按日期范围过滤
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    const [start, end] = dateRange.value
    batches = batches.filter(batch => {
      // 使用批次的开始时间进行过滤
      const batchStartDate = new Date(batch.startTime)
      return batchStartDate >= start && batchStartDate <= end
    })
  }
  
  return batches
})

// 分页后的批次
const paginatedBatches = computed(() => {
  isTableLoading.value = true; // 开始加载
  const start = (batchCurrentPage.value - 1) * batchPageSize.value
  const end = start + batchPageSize.value
  
  const result = filteredBatches.value.slice(start, end);
  
  // 加载完成
  nextTick(() => {
    isTableLoading.value = false;
  });
  
  return result;
})

// 监听分页后的批次，自动展开所有批次
watch(paginatedBatches, (newBatches) => {
  expandedBatches.value = newBatches.map(batch => batch.batchId)
}, { immediate: true })

// 格式化日期函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化短日期（只显示时间）
const formatShortDate = (date: string) => {
  return dayjs(date).format('MM-DD HH:mm')
}

// 处理日期变化
const handleDateChange = () => {
  currentPage.value = 1
  batchCurrentPage.value = 1
  // 添加加载状态
  isTableLoading.value = true
  
  // 延迟一下释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false
    }, 300)
  })
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  // 添加加载状态
  isTableLoading.value = true
  
  // 延迟一下释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false
    }, 300)
  })
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 添加加载状态
  isTableLoading.value = true
  
  // 延迟一下释放加载状态
  nextTick(() => {
    setTimeout(() => {
      isTableLoading.value = false
    }, 300)
  })
}

// 获取产品编码
const getProductCode = (keyCode: string) => {
  const product = productStore.products.find(p => p.keyCode === keyCode)
  return product?.productCode || '-'
}

// 导出记录
const handleExport = () => {
  if (filteredRecords.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  try {
    // 准备CSV数据
    const headers = ['扫描时间', '扫码信息', '产品编码', '产品名称', '关键代码']
    const rows = filteredRecords.value.map(record => [
      formatDate(record.scanTime),
      record.scanCode,
      record.productCode,
      record.productName,
      record.keyCode
    ])

    // 组合CSV内容
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n')

    // 创建Blob对象
    const blob = new Blob(['\ufeff' + csvContent], { 
      type: 'text/csv;charset=utf-8;' 
    })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    // 设置文件名（包含日期范围）
    let fileName = '扫码记录'
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      const startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD')
      const endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD')
      fileName += `_${startDate}_${endDate}`
    } else {
      fileName += `_${dayjs().format('YYYY-MM-DD')}`
    }
    fileName += '.csv'
    
    link.setAttribute('href', url)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

// 统计范围选择
const statsRange = ref('7')

// 处理范围变化
const handleRangeChange = () => {
  // 触发图表更新
}

// 计算图表据
const chartData = computed(() => {
  const now = dayjs()
  
  // 根据选择的范围确定开始日期
  let startDate: dayjs.Dayjs
  if (statsRange.value === 'month') {
    startDate = now.startOf('month')
  } else {
    const days = parseInt(statsRange.value)
    startDate = now.subtract(days - 1, 'day').startOf('day')
  }

  const dates: string[] = []
  const counts: number[] = []

  // 生成日期范围内的每日统计
  for (let d = startDate; d.isSameOrBefore(now, 'day'); d = d.add(1, 'day')) {
    const date = d.format('YYYY-MM-DD')
    const count = scanStore.records.filter(record => 
      record.scanTime.startsWith(date)
    ).length

    dates.push(d.format('MM-DD'))
    counts.push(count)
  }

  return { dates, counts }
})

// 图表配置
const chartOption = computed(() => {
  const { dates, counts } = chartData.value
  const maxCount = Math.max(...counts, 10)
  
  return {
    backgroundColor: '#ffffff',
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: 'rgba(0, 0, 0, 0.1)',
      borderWidth: 1,
      padding: [10, 15],
      textStyle: {
        color: '#666'
      },
      formatter: (params: any) => {
        const [param] = params
        return `<div style="font-weight: bold; margin-bottom: 5px;">${param.name} 日</div>
                <div style="display: flex; align-items: center;">
                  <span style="display: inline-block; width: 10px; height: 10px; background: #409EFF; margin-right: 5px; border-radius: 50%;"></span>
                  扫码次数：${param.value}
                </div>`
      }
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#999',
        fontSize: 12,
        margin: 15
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: maxCount,
      splitNumber: 4,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: '#999',
        fontSize: 12,
        margin: 15
      },
      splitLine: {
        lineStyle: {
          color: '#f5f5f5',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '扫码次数',
        type: 'line',
        data: counts,
        smooth: true,
        symbol: 'circle',
        symbolSize: 10,
        showSymbol: false,
        emphasis: {
          scale: true,
          focus: 'series',
          itemStyle: {
            color: '#fff',
            borderColor: '#409EFF',
            borderWidth: 2,
            shadowColor: 'rgba(0, 0, 0, 0.2)',
            shadowBlur: 10
          }
        },
        itemStyle: {
          color: '#409EFF',
          borderWidth: 2,
          borderColor: '#fff'
        },
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#409EFF'
              },
              {
                offset: 1,
                color: '#36CE9E'
              }
            ]
          }
        },
        areaStyle: {
          opacity: 0.8,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64, 158, 255, 0.15)'
              },
              {
                offset: 0.5,
                color: 'rgba(54, 206, 158, 0.15)'
              },
              {
                offset: 1,
                color: 'rgba(255, 255, 255, 0.05)'
              }
            ]
          }
        }
      }
    ],
    animation: true,
    animationDuration: 1500,
    animationEasing: 'cubicInOut'
  }
})

// 更新图表容器样式
const chartContainerStyle = {
  height: '400px',
  padding: '20px 0'
}

// 新增的删除选中功能
const selectedRows = ref<ScanRecord[]>([])
const batchSelectedMap = ref<Map<string, ScanRecord[]>>(new Map())

const handleDeleteSelected = async () => {
  if (!selectedRows.value.length) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 删除选中的记录
    const selectedIds = selectedRows.value.map(row => row.id)
    scanStore.deleteRecords(selectedIds)
    selectedRows.value = []
    // 清空批次选择缓存
    batchSelectedMap.value.clear()
    ElMessage.success('删除成功')
  } catch {
    // 用户取消操作
  }
}

const handleSelectionChange = (rows: ScanRecord[]) => {
  selectedRows.value = rows
}

const handleBatchSelectionChange = (rows: ScanRecord[], batchId: string) => {
  // 更新特定批次的选中记录
  if (rows.length === 0) {
    batchSelectedMap.value.delete(batchId)
  } else {
    batchSelectedMap.value.set(batchId, rows)
  }
  
  // 汇总所有批次的选中记录
  const allSelected: ScanRecord[] = []
  batchSelectedMap.value.forEach(records => {
    allSelected.push(...records)
  })
  
  selectedRows.value = allSelected
}

// 添加格式化批次ID函数
const formatBatchId = (batchId: string) => {
  if (!batchId) return '-';
  
  // 使用不同的方式提取批次ID，确保唯一性
  if (batchId.startsWith('BATCH-')) {
    const timestamp = batchId.substring(6);
    
    // 使用时间戳的后6位，确保每个批次显示不同
    // 将时间戳转为数字后取模，确保结果在合理范围内
    const timestampNum = parseInt(timestamp);
    if (!isNaN(timestampNum)) {
      // 创建一个由数字和字母组成的唯一标识
      const lastDigits = timestamp.substring(timestamp.length - 6);
      // 添加分隔符，使其更易读
      return lastDigits.substring(0, 3) + '-' + lastDigits.substring(3);
    }
    
    // 如果无法解析为数字，使用原来的方法
    return timestamp.substring(timestamp.length - 6);
  }
  
  // 对于其他格式的ID，使用后6位
  if (batchId.length > 6) {
    return batchId.substring(batchId.length - 6);
  }
  
  return batchId;
}
</script>

<style scoped>
.scan-records {
  padding: 20px;
}

.chart-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
}

.chart {
  width: 100%;
  height: 100%;
}

.header {
  margin-bottom: 20px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-records {
  margin-top: 20px;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-id {
  font-weight: bold;
}

.batch-time {
  color: #909399;
  margin: 0 10px;
}

.batch-code {
  background-color: #e6a23c;
}

.batch-product {
  color: #606266;
}

.batch-count {
  background-color: #f56c6c;
}

.table-actions {
  margin-bottom: 10px;
}

/* 展开行样式 */
.expanded-row {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin: 10px;
}

.expanded-row p {
  margin: 8px 0;
  line-height: 1.5;
}
</style> 